import { ModalForm, ProFormCascader, ProFormDigit, ProFormText } from '@ant-design/pro-components';
import type { ModalFormProps, ProFormInstance } from '@ant-design/pro-components';
import { useEffect, useRef, useState } from 'react';
import { isEmpty } from '@/utils';

interface IProps {
  actionType: 'add' | 'edit';
  treeData: MENU.MenuType[];
  onFinished: ModalFormProps['onFinish'];
  triggerEl: ModalFormProps['trigger'];
  editMenuInfo?: MENU.MenuType;
}

interface Option {
  value: string;
  label: string;
  children?: Option[];
}

// 加载级联框下拉选项
function loadMenuOptions(data: MENU.MenuType[]): Option[] {
  return data.reduce((result: Option[], cur) => {
    const tempOption: Option = {
      value: cur.id,
      label: cur.menuName,
      children: [],
    };
    if (!isEmpty(cur.children)) {
      tempOption.children = loadMenuOptions(cur.children as MENU.MenuType[]);
    }
    result.push(tempOption);
    return result;
  }, []);
}

function getSelectMenuIds({
  data,
  findId,
  cacheIdArr = [],
  level = 0,
}: {
  data: MENU.MenuType[];
  findId: string;
  cacheIdArr?: string[];
  level?: number;
}): string[] {
  for (const item of data) {
    if (item.id === findId) {
      // cacheIdArr[level] = item.id;
      break;
    }
    if (!isEmpty(item.children)) {
      getSelectMenuIds({
        data: item.children || [],
        cacheIdArr,
        level: level + 1,
        findId,
      });
      cacheIdArr[level] = item.id;
    }
  }
  return cacheIdArr;
}

const AddOrEditMenuModal: React.FC<IProps> = ({
  actionType,
  treeData,
  onFinished,
  triggerEl,
  editMenuInfo,
}) => {
  const [menuOption, setMenuOption] = useState<Option[]>([]);
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const formRef = useRef<ProFormInstance>();

  useEffect(() => {
    setMenuOption(loadMenuOptions(treeData));
  }, [treeData]);

  const setEditInfo = () => {
    if (editMenuInfo) {
      formRef.current?.setFieldsValue({
        ...editMenuInfo,
        icon: editMenuInfo.icon,
        pid:
          editMenuInfo.pid === '0'
            ? ['0']
            : getSelectMenuIds({ data: treeData, findId: editMenuInfo.id }),
      });
    }
  };

  return (
    <>
      <ModalForm
        formRef={formRef}
        open={modalVisible}
        onOpenChange={setModalVisible}
        modalProps={{
          destroyOnClose: true,
          width: 520,
          forceRender: actionType === 'edit',
        }}
        title={actionType === 'add' ? '新增菜单' : '编辑菜单'}
        trigger={
          <div
            onClick={() => {
              setModalVisible(true);
              if (actionType === 'edit') setEditInfo();
            }}
          >
            {triggerEl}
          </div>
        }
        onFinish={onFinished}
      >
        <ProFormCascader
          name="pid"
          disabled={actionType === 'edit'}
          label="父级菜单"
          rules={[
            {
              required: true,
              message: '必填',
            },
          ]}
          fieldProps={{
            changeOnSelect: true,
            options: [{ value: '0', label: '根菜单节点' }, ...menuOption],
          }}
        />
        <ProFormText
          name="menuName"
          label="菜单名称"
          rules={[
            {
              required: true,
              message: '必填',
            },
          ]}
        />
        <ProFormText
          name="menuCode"
          label="菜单编码"
          rules={[
            {
              required: true,
              message: '必填',
            },
          ]}
        />
        <ProFormText
          name="link"
          label="菜单链接"
          rules={[
            {
              required: true,
              message: '必填',
            },
          ]}
        />
        <ProFormText name="icon" label="菜单图标" />
        <ProFormDigit
          name="order"
          label="菜单顺序"
          min={1}
          initialValue={1}
          rules={[
            {
              required: true,
              message: '必填',
            },
          ]}
        />
      </ModalForm>
    </>
  );
};
export default AddOrEditMenuModal;
